package com.testyourshell.service.security;

import java.util.Collection;
import java.util.HashSet;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.testyourshell.data.Role;
import com.testyourshell.data.TestYourShellUserDetails;
import com.testyourshell.exception.user.UserNotFoundException;
import com.testyourshell.model.user.User;
import com.testyourshell.service.user.UserService;

@Service("securityService")
public class SecurityServiceImpl implements SecurityService {

	@Autowired
	UserService userService;

	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {
		User user = null;

		try {
			user = userService.findByUsername(username);
		} catch (UserNotFoundException ex) {
			throw new UsernameNotFoundException("User " + username
					+ "is not found.");
		}

		return fillUserDetails(user);
	}

	private TestYourShellUserDetails fillUserDetails(User user) {
		TestYourShellUserDetails userDetails = new TestYourShellUserDetails();

		userDetails.setUsername(user.getUsername());
		userDetails.setPassword(user.getPassword());

		Collection<Role> roles = user.getRoles();
		Collection<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
		for (Role role : roles) {
			authorities.add(new SimpleGrantedAuthority(role.name()));
		}
		userDetails.setAuthorities(authorities);

		userDetails.setAccountNonExpired(true);
		userDetails.setAccountNonLocked(true);
		userDetails.setCredentialsNonExpired(true);
		userDetails.setEnabled(true);

		return userDetails;
	}

}
